/*
 *
 *
 *  Copyright (C) Microsoft Corporation.  All rights reserved
 *
 *
 */

#region Using directives

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Diagnostics;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;
using WControls = System.Web.UI.WebControls;
using Microsoft.Crm.DataBindining;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;

#endregion

namespace CRMScenarios
{
    partial class AttachDoc : CRMScenarios.BaseUserControl
	{
        string[][] ActivityComboMapping = null; 
        ActionsPane _parentPane = null;       
        
        private string ActivityName()
        {
            int iIndex = index(ref ActivityComboMapping[0], (string)this.cmboxActivity.SelectedItem);
            return ((iIndex != -1) ? (ActivityComboMapping[1][iIndex]) : (string.Empty));
        }

        private void ActivateAttachDoc()
        {
            this.panel1.Enabled = true;
            this.rBtnThisRec.Enabled = true;
            this.rBtnRelated.Enabled = true;
            this.rBtnThisRec.Checked = true;
            this.cmBoxRelated.Items.Clear();

            MakeItLookBusy(global::CRMScenarios.Resources.GetEntityList);
            RelatedComboMapping = CrmConnector.GetRelatedEntityList(this.MainEntityName(), PrivilegeType.Read);
            NotBusyAnyMore();

            this.cmBoxRelated.Items.Clear();
            string[] relatedEntityList = RelatedComboMapping[0]; //dont have to check for null. It always returns NonNull.
            if ((relatedEntityList == null) || (relatedEntityList.Length == 0))
            {
                FlagErrorOrWarning(global::CRMScenarios.Resources.NoRelatedEntitiesConfigured, InfoOptions.Warning);
                return;
            }
            populateCombo(ref this.cmBoxRelated, relatedEntityList);
            this.cmBoxRelated.SelectedItem = string.Empty;
            ActivateAttachAsNeeded(MainEntityName(), ref thisRecord);
        }

		public AttachDoc(Object objParentPane)
		{
			InitializeComponent();
            _parentPane = (ActionsPane)objParentPane;
            
            _parentPane.Controls.Clear();
            _parentPane.Controls.Add(_parentPane.AttachPanel);

            this.SetStyle(ControlStyles.UserPaint | ControlStyles.SupportsTransparentBackColor, true);
            BackColor = Color.FromArgb(0, 0, 0, 0);
            this.UpdateStyles();
			this.SizeChanged += new EventHandler(AttachDoc_SizeChanged);
            FlagErrorOrWarning(global::CRMScenarios.Resources.Initializing, InfoOptions.Busy);

            this.cmBoxRelated.SelectedIndexChanged += new System.EventHandler(this.cmBoxRelated_SelectedIndexChanged);
            this.textBoxLookForText.TextChanged += new System.EventHandler(this.tBoxSearchFor_TextChanged);
            this.buttonGoSearch.Click += new System.EventHandler(this.buttonGoSearch_Click);
            // for some wierd reasons, we have to have seperate labels for radioButtons. 
            // So lets have some nice event handlers for the same.

            lblRBtnAttAsActivty.Click += new EventHandler(LabelClickHandlerAttachAsActivity);
            lblRBtnAttAsNote.Click += new EventHandler(LabelClickHandlerAttachAsNote);
            lblRBtnAttRelated.Click += new EventHandler(LabelClickHandlerRelatedRecord);
            lblRBtnAttThisRec.Click += new EventHandler(LabelClickHandlerThisRecord);

            lnklblOtherTask.MouseHover += new EventHandler(UnderLineTheLabel);
            lnklblWarning.MouseHover += new EventHandler(UnderLineTheLabel);
            lnkLblTips.MouseHover += new EventHandler(UnderLineTheLabel);

            lnklblOtherTask.MouseLeave += new EventHandler(UndoUnderLineTheLabel);
            lnklblWarning.MouseLeave += new EventHandler(UndoUnderLineTheLabel);
            lnkLblTips.MouseLeave += new EventHandler(UndoUnderLineTheLabel);

            listViewOfRelatedRecordDetails.CellDoubleClick += new DataGridViewCellEventHandler(listViewOfRelatedRecordDetails_DoubleClick);
            listViewOfRelatedRecordDetails.SelectionChanged += new EventHandler(listViewRelatedRec_SelectedIndexChanged);
            listViewOfRelatedRecordDetails.CellMouseEnter += new DataGridViewCellEventHandler(dataGridView_CellMouseEnter);
            listViewOfRelatedRecordDetails.DataError += new DataGridViewDataErrorEventHandler(RelatedGridDataError);

            this.panel1.MouseDown += new MouseEventHandler(panel1_MouseDown);
            this.panel2.MouseDown += new MouseEventHandler(panel2_MouseDown);

            textBoxLookForText.KeyDown += new KeyEventHandler(textBoxLookForText_KeyDown);
            this.panelOtherTask.MouseDown += new MouseEventHandler(panelOtherTask_MouseDown);
            this.firstPagePic.Click += new System.EventHandler(this.firstPagePic_Click);
            this.previousPagePic.Click += new System.EventHandler(this.previousPagePic_Click);
            this.nextPagePic.Click += new System.EventHandler(this.nextPagePic_Click);
            this.PicBtnBack.Click += new System.EventHandler(this.PicBtnBack_Click);
            this.PicBtnForward.Click += new System.EventHandler(this.PicBtnForward_Click);

            // isnt this a dummy creation?
            this.lblNoRecordFound = new Label();
            DisableAllControls();
		}

        void panel2_MouseDown(object sender, MouseEventArgs e)
        {
            panel2.Focus();
        }

        void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            panel1.Focus();
        }

		void AttachDoc_SizeChanged(object sender, EventArgs e)
		{
            if (Width < (lblHeading.Width + (2 * xPadding) + 8))
			{
				return;
			}

            lblHeading.Location = new Point(xPadding, lblHeading.Location.Y);
			lblAttachAs.Location = new Point(xPadding, lblAttachAs.Location.Y);
			lblAttachTo.Location = new Point(xPadding, lblAttachTo.Location.Y);
			labelLookFor.Location = new Point(xPadding, labelLookFor.Location.Y);
			labelLookIn.Location = new Point(xPadding, labelLookIn.Location.Y);
			lblSelectHeading.Location = new Point(xPadding, lblSelectHeading.Location.Y);
   
            rBtnActivity.Location = new Point(xPadding, rBtnActivity.Location.Y);
            lblRBtnAttAsActivty.Location = new Point(rBtnActivity.Location.X + rBtnActivity.Width, lblRBtnAttAsActivty.Location.Y);

			rBtnNote.Location = new Point(xPadding, rBtnNote.Location.Y);
            lblRBtnAttAsNote.Location = new Point(rBtnNote.Location.X + rBtnNote.Width, lblRBtnAttAsNote.Location.Y);

			rBtnRelated.Location = new Point(xPadding, rBtnRelated.Location.Y);
            lblRBtnAttRelated.Location = new Point(rBtnRelated.Location.X + rBtnRelated.Width, lblRBtnAttRelated.Location.Y);

			rBtnThisRec.Location = new Point(xPadding, rBtnThisRec.Location.Y);
            lblRBtnAttThisRec.Location = new Point(rBtnThisRec.Location.X + rBtnThisRec.Width, lblRBtnAttThisRec.Location.Y);

            panelOtherTask.Size = new Size(Width - 2 * xPadding, panelOtherTask.Size.Height);
            panelOtherTask.Location = new Point(xPadding, panelOtherTask.Location.Y);
            lnklblWarning.Size = new Size(panelOtherTask.Width - picWarning.Width - 2 * xPadding, lnklblWarning.Height);
            lnklblWarning.Location = new Point(2 * xPadding + picWarning.Width, lnklblWarning.Location.Y);
            lnkLblTips.Location = new Point(2 * xPadding + picHelp.Width, lnkLblTips.Location.Y);

            horizontalLine1.Size = new Size(Width - 2 * xPadding, horizontalLine1.Size.Height);
            horizontalLine2.Size = new Size(Width - 2 * xPadding, horizontalLine2.Size.Height);
            horizontalLine3.Size = new Size(Width - 2 * xPadding, horizontalLine3.Size.Height);
            horizontalLine1.Location = new Point(xPadding, horizontalLine1.Location.Y);
            horizontalLine2.Location = new Point(xPadding, horizontalLine2.Location.Y);
            horizontalLine3.Location = new Point(xPadding, horizontalLine3.Location.Y);

            btnLookup.Location = new Point(xPadding + lblRBtnAttRelated.Location.X, btnLookup.Location.Y);
            
			comboBoxEntityTypeLookFor.Size = new Size(Width - labelLookIn.Width - 3 * xPadding, comboBoxEntityTypeLookFor.Height);
			comboBoxEntityTypeLookFor.Location = new Point(Width - xPadding - comboBoxEntityTypeLookFor.Width, comboBoxEntityTypeLookFor.Location.Y);
			
			btnAttach.Location = new Point(Width - btnAttach.Width - xPadding, btnAttach.Location.Y);
			buttonGoSearch.Location= new Point(Width - buttonGoSearch.Width - xPadding, buttonGoSearch.Location.Y);

            textBoxLookForText.Size = new Size(Width - buttonGoSearch.Width - labelLookFor.Width - 4 * xPadding, textBoxLookForText.Size.Height);
            textBoxLookForText.Location = new Point(2 * xPadding + labelLookFor.Width, textBoxLookForText.Location.Y);

			cmBoxRelated.Size = new Size(Width - rBtnRelated.Width - lblRBtnAttRelated.Width - 3 * xPadding, cmBoxRelated.Size.Height);
			cmBoxRelated.Location = new Point(Width - xPadding - cmBoxRelated.Width, cmBoxRelated.Location.Y);


			cmboxActivity.Size = new Size(Width - rBtnActivity.Width - lblRBtnAttAsActivty.Width - 3 * xPadding, cmboxActivity.Height);
			cmboxActivity.Location = new Point(Width - cmboxActivity.Width - xPadding, cmboxActivity.Location.Y);

            panel1.Size = new Size(Width, panel1.Height);
            panel2.Size = new Size(Width, panel2.Height);


            int TotalWidthOfVisibleColumns = 0;
            foreach (DataGridViewColumn s in this.listViewOfRelatedRecordDetails.Columns)
            {
                if ((s != null) && (s.Visible))
                {
                    TotalWidthOfVisibleColumns += s.Width;
                }
            }
            listViewOfRelatedRecordDetails.Size = new Size(Width - 2 * xPadding, listViewOfRelatedRecordDetails.Height);
            listViewOfRelatedRecordDetails.Location = new Point(xPadding, listViewOfRelatedRecordDetails.Location.Y);
            if ((TotalWidthOfVisibleColumns > listViewOfRelatedRecordDetails.Width))
            {
                TotalWidthOfVisibleColumns = 0;
                foreach (DataGridViewColumn s in this.listViewOfRelatedRecordDetails.Columns)
                {
                    if ((s != null) && (s.Visible))
                    {
                        s.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        TotalWidthOfVisibleColumns += s.Width;
                    }
                }
            }
            else if ((TotalWidthOfVisibleColumns < listViewOfRelatedRecordDetails.Width))
            {
                foreach (DataGridViewColumn s in this.listViewOfRelatedRecordDetails.Columns)
                {
                    if ((s != null) && (s.Visible))
                    {
                        s.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    }
                }
            }

            lblNoRelRecords.Location = new Point(listViewOfRelatedRecordDetails.Location.X + ((listViewOfRelatedRecordDetails.Width - lblNoRelRecords.Width) / 2), lblNoRelRecords.Location.Y);

            nextPagePic.Location = new Point(Width - xPadding - nextPagePic.Width, nextPagePic.Location.Y);
            lblPageNum.Location = new Point(nextPagePic.Location.X - lblPageNum.Width, lblPageNum.Location.Y);
            previousPagePic.Location = new Point(lblPageNum.Location.X - previousPagePic.Width, previousPagePic.Location.Y);
            firstPagePic.Location = new Point(previousPagePic.Location.X - firstPagePic.Width, firstPagePic.Location.Y);

            PicBtnForward.Location = new Point(this.Width - PicBtnForward.Width - xPadding, PicBtnForward.Location.Y);
            PicBtnBack.Location = new Point(PicBtnForward.Location.X - PicBtnBack.Width - xPadding, PicBtnBack.Location.Y);

			Refresh();
		}

        public override void initializeControls(object application, object activeOne)
        {
            Application = application;
            ActiveOne = activeOne;
            thisRecord = null;
            // enable the panel for other tasks.
            this.panelOtherTask.Enabled = true;
            // the following is done so as to activate the lower part at the first instance itself
            this.rBtnThisRec.Checked = false;

            // done once!!

            // Combo Search
            comboBoxEntityTypeLookFor.Items.Clear();
            MainComboMapping = CrmConnector.getEntityListFromCRM(PrivilegeType.Read);
            string[] entityList = MainComboMapping[0];
            if ((entityList == null) || (entityList.Length == 0))
            {
                FlagErrorOrWarning(global::CRMScenarios.Resources.NoEntitiesConfigured, InfoOptions.Warning);
                return;
            }
            populateListBox(ref this.comboBoxEntityTypeLookFor, entityList);
            this.comboBoxEntityTypeLookFor.SelectedItem = string.Empty;
            this.comboBoxEntityTypeLookFor.Enabled = true;

            //TextBox Search
            this.textBoxLookForText.MaxLength = 100;
            this.textBoxLookForText.Text = string.Empty;
            this.textBoxLookForText.AutoCompleteMode = AutoCompleteMode.Suggest;
            this.textBoxLookForText.AutoCompleteSource = AutoCompleteSource.CustomSource;
            TextBoxCacheSource = new AutoCompleteStringCollection();
            this.textBoxLookForText.AutoCompleteCustomSource = TextBoxCacheSource;
            toolTipForTextBox = new ToolTip();
            toolTipForTextBox.AutoPopDelay = 5000;
            toolTipForTextBox.InitialDelay = 100;
            toolTipForTextBox.ReshowDelay = 500;
            toolTipForTextBox.SetToolTip(textBoxLookForText, string.Empty);

            this.listViewOfRelatedRecordDetails.Columns.Clear();
            DisablePaging();
            lblNoRelRecords.Visible = lblNoRelRecords.Enabled = false;

            //have to re-assign the image of lookup button. //TODO
            this.FlagErrorOrWarning(string.Empty, InfoOptions.Free);


            rBtnThisRec.BackColor = rBtnRelated.BackColor;
        }

        void LabelClickHandlerThisRecord(object sender, EventArgs e)
        {
            // this check stands for checking whether the panel is enabled or not.
            if ((panel1.Enabled == true) && (rBtnThisRec.Enabled == true))
            {
                if (rBtnThisRec.Checked == true)
                {
                    return;
                }
                rBtnThisRec.Checked = !(rBtnThisRec.Checked);
                rBtnRelated.Checked = !(rBtnThisRec.Checked);
            }
        }

        void LabelClickHandlerRelatedRecord(object sender, EventArgs e)
        {
            // this check stands for checking whether the panel is enabled or not.
            if ((panel1.Enabled == true) && (rBtnRelated.Enabled == true))
            {
                if (rBtnRelated.Checked == true)
                {
                    return;
                }

                rBtnRelated.Checked = !(rBtnRelated.Checked);
                rBtnThisRec.Checked = !(rBtnRelated.Checked);
            }
        }

        void LabelClickHandlerAttachAsActivity(object sender, EventArgs e)
        {
            // this check stands for checking whether the panel is enabled or not.
            if ((panel2.Enabled == true) && (rBtnActivity.Enabled == true))
            {
                if (rBtnActivity.Checked == true)
                {
                    return;
                }

                rBtnActivity.Checked = !(rBtnActivity.Checked);
                rBtnNote.Checked = !(rBtnActivity.Checked);

            }
        }

        void LabelClickHandlerAttachAsNote(object sender, EventArgs e)
        {
            // this check stands for checking whether the panel is enabled or not.
            if ((panel2.Enabled == true) && (rBtnNote.Enabled == true))
            { 
                if (rBtnNote.Checked == true)
                {
                    return;
                }

                rBtnNote.Checked = !(rBtnNote.Checked);
                rBtnActivity.Checked = !(rBtnNote.Checked);
            }
        }

        public void sizeChange(int pWidth, int pHeight)
        {
            this.Location = new Point(0, 0);
            this.Size = new Size(pWidth, pHeight);
        }
                
        private void lnkLblInsertFld_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
            ((ActionsPane)this.Parent).changeScenario(1, comboBoxEntityTypeLookFor.Text,
                textBoxLookForText.Text, ref thisRecord, RefreshOption.FromLink);// hard coded '2' for scenario attach doc.
                                                         // so we need to give code for insert fields.
		}

        public override void DisableControlsWhileLookUp()
        {
            this.FlagErrorOrWarning(string.Empty, InfoOptions.Free);
            this.cmBoxRelated.Enabled = false;
            this.panel1.Enabled = false;
            this.panel2.Enabled = false;
            this.btnAttach.Enabled = false;
            this.btnLookup.Enabled = false;
            this.buttonGoSearch.Enabled = false;
            DisablePaging();
        }

        DateTime start;
        DateTime end;
        bool CancelApp = true;

        public void AppointmentSchedulingInf(DateTime startTime, DateTime endTime)
        {
            start = startTime;
            end = endTime;
            CancelApp = false;
        }

		private void btnAttach_Click(object sender, EventArgs e)
        {
            #region USER INTERACTION - IMPORTANT
            if (OfficeApi.IsDocumentSaved(ActiveOne) != true)
            {
                if (MessageBox.Show(global::CRMScenarios.Resources.SaveTheDoc, global::CRMScenarios.Resources.DialogBoxTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    return;
                }

                OfficeApi.SaveTheDocument(ActiveOne);
                if (OfficeApi.IsDocumentSaved(ActiveOne) != true)
                {
                    Util.ShowError(global::CRMScenarios.Resources.SaveFailed);
                    return;
                }
            }

            //if (!CrmConnector.IsSecureConnection())
            //{
            //    if (Util.AskQues(global::CRMScenarios.Resources.InsecureChannelWarning) == DialogResult.Cancel)
            //    {
            //        FlagErrorOrWarning(global::CRMScenarios.Resources.AttachAborted, InfoOptions.Warning);
            //        return;
            //    }
            //}

            MakeItLookBusy(global::CRMScenarios.Resources.AttachingTheDocument);

            #endregion 

            string fullQualifiedFilePath = OfficeApi.GetFullQualifiedFilePath(ActiveOne);
            string title = string.Empty;
            if (Application is Word.Application)
            {
                title = global::CRMScenarios.Resources.WdDoc;
            }
            else if (Application is Excel.Application)
            {
                title = global::CRMScenarios.Resources.ExDoc;
            }
            btnAttach.Enabled = false;

            bool success = false;
            if (this.rBtnNote.Checked == true)
            {
                string documentName = OfficeApi.GetDocumentName(ActiveOne);
                if (rBtnThisRec.Checked == true)
                {
                    Guid guid = (System.Guid)CrmConnector.GetAttribute(ref thisRecord, (string)(CrmConnector.GetEntityMetaData(this.MainEntityName()).PrimaryKey));
                    success = CrmConnector.AttachDocumentAsNote(this.MainEntityName(), guid, fullQualifiedFilePath, title, documentName);
                }
                if (rBtnRelated.Checked == true)
                {
                    Guid guid = (System.Guid)CrmConnector.GetAttribute(ref selectedRelatedRecord, (string)(CrmConnector.GetEntityMetaData(this.RelatedEntityName()).PrimaryKey));
                    success = CrmConnector.AttachDocumentAsNote(this.RelatedEntityName(), guid, fullQualifiedFilePath, title, documentName);
                }
            } 
            else if (this.rBtnActivity.Checked == true)
            {
                object optional = null;
                if (this.ActivityName() == "appointment")
                {
                    CancelApp = true;
                    Scheduling_Information appDetails = new Scheduling_Information(this);
                    appDetails.ShowDialog();
                    if (CancelApp)
                    {
                        FlagErrorOrWarning(global::CRMScenarios.Resources.AttachAborted, InfoOptions.Free);
                        NotBusyAnyMore();
                        btnAttach.Enabled = true;
                        return;
                    }
                    optional = (object)new DateTime[] { start, end };
                }
            
                if (rBtnThisRec.Checked == true)
                {
                    success = CrmConnector.AttachToNewActivity(this.MainEntityName(), ref thisRecord, fullQualifiedFilePath, this.ActivityName(), title, ref optional);
                }
                if (rBtnRelated.Checked == true)
                {
                    success = CrmConnector.AttachToNewActivity(this.RelatedEntityName(), ref selectedRelatedRecord, fullQualifiedFilePath, this.ActivityName(), title, ref optional);
                }
            }

            if (success == true)
            {
                FlagErrorOrWarning(global::CRMScenarios.Resources.DocumentAttachedSuccessfully, InfoOptions.Success);
            }
            else
            {
                FlagErrorOrWarning(global::CRMScenarios.Resources.ErrorAttachingDoc, InfoOptions.Error);
            }

            NotBusyAnyMore();
            btnAttach.Enabled = true;
		}        

        private void cmBoxLookIn_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ChangingLookupComboProgrammatically == true)
            {
                return;
            }

            DisableAllControls();

            RefreshMetaDataIfNeeded();
            this.PicBtnBack.Enabled = GoBackAndForth.CanGoBackward();
            this.PicBtnForward.Enabled = GoBackAndForth.CanGoFroward();
            this.picHelp.Enabled = true;
            thisRecord = null;
            this.comboBoxEntityTypeLookFor.Enabled = true;
            this.textBoxLookForText.Text = string.Empty;
            textBoxLookForText.Font = new Font(textBoxLookForText.Font.FontFamily, textBoxLookForText.Font.Size, FontStyle.Regular, GraphicsUnit.Pixel);
            textBoxLookForText.Click -= new EventHandler(textBoxLookForText_Click);
            toolTipForTextBox.SetToolTip(textBoxLookForText, string.Empty);
            this.textBoxLookForText.Enabled = true;
            this.cmBoxRelated.Items.Clear();
            this.listViewOfRelatedRecordDetails.Columns.Clear();
            currentRelatedBec = null;
            UpDateTxtBoxCache();
            buttonGoSearch.Enabled = true;
            this.FlagErrorOrWarning(string.Empty, InfoOptions.Free);
        }        

        public override void ActivateAttachAsNeeded(string entityType, ref BusinessEntity be)
        {
            if (be != null)
            {
                panel2.Enabled = true;
                rBtnNote.Checked = rBtnNote.Enabled = CrmConnector.CanAttachNote(entityType);
                rBtnActivity.Enabled = CrmConnector.CanAttachActivity(entityType);
                rBtnActivity.Checked = !rBtnNote.Checked;
                cmboxActivity.Enabled = rBtnActivity.Checked;

                if ((!rBtnNote.Enabled) && (!rBtnActivity.Enabled))
                {
                    btnAttach.Enabled = false;
                    cmboxActivity.Enabled = false;
                    panel2.Enabled = false;
                    FlagErrorOrWarning(global::CRMScenarios.Resources.NoAttachOptions, InfoOptions.Warning);
                }
                else
                {
                    btnAttach.Enabled = true;
                }
            }
            else
            {
                panel2.Enabled = false;
                cmboxActivity.Enabled = false;
                btnAttach.Enabled = false;
            }

            if ((rBtnActivity.Checked) && (rBtnActivity.Enabled))
            {
                rBtnActivity_CheckedChanged(null, null);
            }

        }

        private void ActivateAttachAs(bool yesOrNo)
        {
            this.panel2.Enabled = yesOrNo;
            this.cmboxActivity.Enabled = yesOrNo;
            this.rBtnNote.Enabled = yesOrNo;
            this.rBtnActivity.Enabled = yesOrNo;
            this.rBtnNote.Checked = yesOrNo;
            this.btnAttach.Enabled = yesOrNo;
        }

        private void rBtnThisRec_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rBtnThisRec.Checked == true)
            {
                FlagErrorOrWarning(string.Empty, InfoOptions.Free);
                this.cmBoxRelated.Enabled = false;
                this.listViewOfRelatedRecordDetails.Columns.Clear();
                DisablePaging();
                lblNoRelRecords.Visible = lblNoRelRecords.Enabled = false;
                this.listViewOfRelatedRecordDetails.Enabled = false;
                this.btnLookup.Enabled = false;
                this.rBtnActivity.Enabled = true;
                this.rBtnNote.Enabled = true;
                this.rBtnNote.Checked = true;
                ActivateAttachAsNeeded(MainEntityName(), ref thisRecord);
            }
        }

        private void rBtnRelated_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rBtnRelated.Checked == true)
            {
                FlagErrorOrWarning(string.Empty, InfoOptions.Free);
                this.cmBoxRelated.Enabled = true;
                if ((cmBoxRelated.Text != null) && (cmBoxRelated.Text != string.Empty))
                {
                    PageChange(pageInfo.FirstPage());
                    NotBusyAnyMore();
                    BusinessEntity be = null;
                    if ((currentRelatedBec != null) && (currentRelatedBec.BusinessEntities.Length > 0))
                    {
                        be = currentRelatedBec.BusinessEntities[0];
                    }
                    ActivateAttachAsNeeded(RelatedEntityName(), ref be);
                }
                else
                {
                    ActivateAttachAs(false);
                }
            }
        }

        private void listViewRelatedRec_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (RelatedGridSelectionChangeProgramattically == true)
            {
                return;
            }

            if ((this.rBtnThisRec.Checked == true) || (this.rBtnRelated.Checked == false))
            {
                return;
            }

            if (this.listViewOfRelatedRecordDetails.SelectedRows.Count == 0)
            {
                this.rBtnActivity.Enabled = false;
                this.rBtnNote.Enabled = false;
                this.btnAttach.Enabled = false;
                this.btnLookup.Enabled = false;
                return;
            }

            this.btnLookup.Enabled = !CrmConnector.IsNonMainEntity(RelatedEntityName());

            if ((currentRelatedBec != null) && (currentRelatedBec.BusinessEntities.Length > listViewOfRelatedRecordDetails.SelectedRows[0].Index))
            {
                selectedRelatedRecord = currentRelatedBec.BusinessEntities[this.listViewOfRelatedRecordDetails.SelectedRows[0].Index];
            }
            ActivateAttachAsNeeded(RelatedEntityName(), ref selectedRelatedRecord);
        }       

        public override void getDetailsOfTheEntityAndDisplay(BusinessEntity entity, string entityType)
        {
            thisRecord = entity;
            this.lblNoRecordFound.Visible = false;
            if (entity == null)
            {
                this.tBoxSearchFor_TextChanged(null, null);
                FlagErrorOrWarning(string.Empty, InfoOptions.Free);
                return;
            }

            ChangingLookupComboProgrammatically = true;
            this.comboBoxEntityTypeLookFor.SelectedItems.Clear();
            this.comboBoxEntityTypeLookFor.SelectedItem = CrmConnector.NameToDisplay(entityType);
            ChangingLookupComboProgrammatically = false;

            this.textBoxLookForText.Enabled = true;
            this.buttonGoSearch.Enabled = true;

            string strToBeInLookFor = (string)CrmConnector.GetAttribute(ref thisRecord, CrmConnector.GetEntityMetaData(entityType).PrimaryField);
            
            this.textBoxLookForText.Text = (((strToBeInLookFor == null) || (strToBeInLookFor == string.Empty)) ? (global::CRMScenarios.Resources.UnKnown) : (strToBeInLookFor));
            textBoxLookForText.Font = new Font(textBoxLookForText.Font.FontFamily, textBoxLookForText.Font.Size, FontStyle.Underline, GraphicsUnit.Pixel);
            textBoxLookForText.Click -= new EventHandler(textBoxLookForText_Click);
            textBoxLookForText.Click += new EventHandler(textBoxLookForText_Click);
            toolTipForTextBox.SetToolTip(textBoxLookForText, global::CRMScenarios.Resources.CtrlClickToOpen);
            FlagErrorOrWarning(string.Empty, InfoOptions.Free);
            textBoxLookForText.Enabled = true;
            ActivateAttachDoc();
            UpDateTxtBoxCache();
            if (UsingBackForthButton == true)
            {
                return;
            }
            GoBackAndForth.NewRecordEntry(entityType, CrmConnector.GetGuid(ref entity, entityType));
            PicBtnBack.Enabled = GoBackAndForth.CanGoBackward();
            PicBtnForward.Enabled = GoBackAndForth.CanGoFroward();
        }

        private void btnLookup_Click(object sender, EventArgs e)
        {
            MakeItLookBusy(global::CRMScenarios.Resources.FetchingAllDetails);
            getDetailsOfTheEntityAndDisplay(selectedRelatedRecord, RelatedEntityName());
            currentRelatedBec = null;
            selectedRelatedRecord = null;
            this.listViewOfRelatedRecordDetails.Columns.Clear();
            DisablePaging();
            lblNoRelRecords.Visible = lblNoRelRecords.Enabled = false;
            ActivateAttachDoc();
            NotBusyAnyMore();
        }

        private void rBtnNote_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rBtnNote.Checked == true)
            {
                this.cmboxActivity.Items.Clear();
                this.cmboxActivity.Enabled = false;
                this.btnAttach.Enabled = true; ;
            }
            else
            {
                this.btnAttach.Enabled = false;
            }
        }

        private void cmboxActivity_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.btnAttach.Enabled = true;
        }

        private void rBtnActivity_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rBtnActivity.Checked == true)
            {
                MakeItLookBusy(global::CRMScenarios.Resources.GetActivityList);
                this.cmboxActivity.Items.Clear();
                string entityName = ((rBtnThisRec.Checked == true) ? (MainEntityName()) : (RelatedEntityName()));
                ActivityComboMapping = CrmConnector.GetValidActivitiesList(entityName);

                string[] activityList = null;
                if ((ActivityComboMapping == null) || ((activityList = ActivityComboMapping[0]) == null) || (activityList.Length == 0))
                {
                    FlagErrorOrWarning(global::CRMScenarios.Resources.NoActivitiesConfigured, InfoOptions.Warning);
                    NotBusyAnyMore();
                    return;
                }

                populateCombo(ref this.cmboxActivity, activityList);
                if (cmboxActivity.Items.Contains(global::CRMScenarios.Resources.LetterTheCRMEntity))
                {
                    cmboxActivity.SelectedItem = global::CRMScenarios.Resources.LetterTheCRMEntity;
                }
                else
                {
                    this.cmboxActivity.SelectedItem = string.Empty;
                }
                this.cmboxActivity.Enabled = true;
            }
            NotBusyAnyMore();
        }

        private void lblAttachAs_Click(object sender, EventArgs e)
        {

        }

        private void AttachDoc_Load(object sender, EventArgs e)
        {
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        }

        private void GiveWarningOrError()
        {

        }

        private void lnklblWarning_Click(object sender, EventArgs e)
        {
            GiveWarningOrError();
        }

        private void picWarning_Click(object sender, EventArgs e)
        {
            GiveWarningOrError();
        }
        
        private void lnkLblTips_Click(object sender, EventArgs e)
        {
            GiveHelpOrTips("how_IBF_attach.htm");
        }

        private void picHelp_Click(object sender, EventArgs e)
        {
            GiveHelpOrTips("how_IBF_attach.htm");
        }

        private void lnklblOtherTask_Click(object sender, EventArgs e)
        {
            ((ActionsPane)this.Parent).changeScenario(1, MainEntityName(),
                textBoxLookForText.Text, ref thisRecord, RefreshOption.FromLink);
            // hard coded '2' for scenario attach doc.
            // so we need to give code for insert fields.
        }

        private void UndoUnderLineTheLabel(object sender, EventArgs e)
        {
            ((Label)sender).Font = new Font(((Label)sender).Font.FontFamily, ((Label)sender).Font.Size, FontStyle.Regular, GraphicsUnit.Pixel);
            this.Cursor = Cursors.Default;
        }

        private void UnderLineTheLabel(object sender, EventArgs e)
        {
            if (InfoStatus == InfoOptions.Busy)
            {
                return;
            }

            if (((Label)sender).Name == lnklblWarning.Name)
            {
                if (InfoStatus != InfoOptions.Error)
                {
                    return;
                }
            }
            ((Label)sender).Font = new Font(((Label)sender).Font.FontFamily, ((Label)sender).Font.Size, FontStyle.Underline, GraphicsUnit.Pixel);
            this.Cursor = Cursors.Hand;
        }

        void panelOtherTask_MouseDown(object sender, MouseEventArgs e)
        {
            panelOtherTask.Focus();
        }

        void textBoxLookForText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                buttonGoSearch_Click(null, null);
            }
        }

        private void dataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs location)
        {
            mouseLocation = location;
        }

        private void DGView_Click_Two(object sender, EventArgs e)
        {
            BusinessEntity rightClickedRecord = currentRelatedBec.BusinessEntities[mouseLocation.RowIndex];
            MakeItLookBusy(global::CRMScenarios.Resources.OpeningWebPage);
            string Url = CrmConnector.UrlForThisEntity(this.RelatedEntityName(), ref rightClickedRecord);
            NotBusyAnyMore();
            if ((Url == null) || (Url == string.Empty))
            {
                FlagErrorOrWarning(global::CRMScenarios.Resources.BrowserPageNotSupported + cmBoxRelated.Text, InfoOptions.Warning);
                return;
            }
            OpenPage(CrmConnector.UrlForThisEntity(this.RelatedEntityName(), ref rightClickedRecord));
        }

        private void DGView_Click_One(object sender, EventArgs e)
        {
            BusinessEntity rightClickedRecord = currentRelatedBec.BusinessEntities[mouseLocation.RowIndex];
            MakeItLookBusy(global::CRMScenarios.Resources.FetchingAllDetails);
            getDetailsOfTheEntityAndDisplay(rightClickedRecord, this.RelatedEntityName());
            NotBusyAnyMore();
            this.listViewOfRelatedRecordDetails.Columns.Clear();
            this.listViewOfRelatedRecordDetails.Enabled = false;
            DisablePaging();
            lblNoRelRecords.Visible = lblNoRelRecords.Enabled = false;
            if (CBoxSelectAllRelRec != null)
            {
                CBoxSelectAllRelRec.Visible = CBoxSelectAllRelRec.Enabled = false;
            }
        }

        private void tBoxSearchFor_TextChanged(object sender, EventArgs e)
        {
            textBoxLookForText.Click -= new EventHandler(textBoxLookForText_Click);
            toolTipForTextBox.SetToolTip(textBoxLookForText, string.Empty);
            textBoxLookForText.Font = new Font(textBoxLookForText.Font.FontFamily, textBoxLookForText.Font.Size, FontStyle.Regular, GraphicsUnit.Pixel);
        }

        private void textBoxLookForText_Click(object sender, EventArgs e)
        {
            if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                MakeItLookBusy(global::CRMScenarios.Resources.OpeningWebPage);
                string Url = CrmConnector.UrlForThisEntity(this.MainEntityName(), ref thisRecord);
                NotBusyAnyMore();
                if ((Url == null) || (Url == string.Empty))
                {
                    FlagErrorOrWarning(global::CRMScenarios.Resources.BrowserPageNotSupported + comboBoxEntityTypeLookFor.Text, InfoOptions.Warning);
                    return;
                }
                OpenPage(Url);
            }
        }

        private void cmBoxRelated_SelectedIndexChanged(object sender, EventArgs e)
        {
            MakeItLookBusy(global::CRMScenarios.Resources.RetrievingRelRecords);
            PageChange(pageInfo.FirstPage());
            NotBusyAnyMore();
            BusinessEntity be = null;
            if ((currentRelatedBec != null) && (currentRelatedBec.BusinessEntities.Length > 0))
            {
                be = currentRelatedBec.BusinessEntities[0];
            }
            ActivateAttachAsNeeded(RelatedEntityName(), ref be);
        }

        protected override void AddContextMenu()
        {
            ToolStripMenuItem toolStripItem1 = new ToolStripMenuItem();
            toolStripItem1.Text = btnLookup.Text;
            toolStripItem1.Click -= new EventHandler(DGView_Click_One);
            toolStripItem1.Click += new EventHandler(DGView_Click_One);
            ToolStripMenuItem toolStripItem2 = new ToolStripMenuItem();
            toolStripItem2.Text = global::CRMScenarios.Resources.ContextMenuViewInCRM;
            toolStripItem2.Click -= new EventHandler(DGView_Click_Two);
            toolStripItem2.Click += new EventHandler(DGView_Click_Two);
            ContextMenuStrip strip = new ContextMenuStrip();
            foreach (DataGridViewRow row in listViewOfRelatedRecordDetails.Rows)
            {
                row.ContextMenuStrip = strip;
                if (!CrmConnector.IsNonMainEntity(RelatedEntityName()))
                {
                    row.ContextMenuStrip.Items.Add(toolStripItem1);
                }
                row.ContextMenuStrip.Items.Add(toolStripItem2);
                foreach (DataGridViewCell cell in row.Cells)
                {
                    cell.ErrorText = string.Empty;
                    cell.ToolTipText = global::CRMScenarios.Resources.ToolTipRelatedRecordView;
                }
            }
        }

        private void firstPagePic_Click(object sender, EventArgs e)
        {
            PageChange(pageInfo.FirstPage());
        }

        private void previousPagePic_Click(object sender, EventArgs e)
        {
            PageChange(pageInfo.PrevPage());
            //EnablePaging();
        }

        private void nextPagePic_Click(object sender, EventArgs e)
        {
            PageChange(pageInfo.NextPage());
            //EnablePaging();
        }

        private void PicBtnBack_Click(object sender, EventArgs e)
        {
            GoBackAndForth.MoveBackvard();
            string eType = GoBackAndForth.RecordType();
            Guid guid = GoBackAndForth.RecordId();
            MoveBackAndForth(guid, eType);
        }

        private void PicBtnForward_Click(object sender, EventArgs e)
        {
            GoBackAndForth.MoveForward();
            string eType = GoBackAndForth.RecordType();
            Guid guid = GoBackAndForth.RecordId();
            MoveBackAndForth(guid, eType);
        }

        private void listViewOfRelatedRecordDetails_DoubleClick(object sender, EventArgs e)
        {
            if (((DataGridViewCellEventArgs)e).RowIndex < 0)
            {
                return;
            }

            if (CrmConnector.IsNonMainEntity(RelatedEntityName()))
            {
                return;
            }

            if (this.listViewOfRelatedRecordDetails.SelectedRows.Count == 1)
            {
                BusinessEntity entity = currentRelatedBec.BusinessEntities[this.listViewOfRelatedRecordDetails.SelectedRows[0].Index];
                MakeItLookBusy(global::CRMScenarios.Resources.OpeningWebPage);
                string Url = CrmConnector.UrlForThisEntity(this.RelatedEntityName(), ref entity);
                NotBusyAnyMore();
                if ((Url == null) || (Url == string.Empty))
                {
                    FlagErrorOrWarning(global::CRMScenarios.Resources.BrowserPageNotSupported + this.RelatedEntityName(), InfoOptions.Warning);
                    return;
                }
                OpenPage(Url);
            }
        }

        private void buttonGoSearch_Click(object sender, EventArgs eventArg)
        {
            ArrayList selectedEntities = new ArrayList();
            _parentPane.SearchFromInsert = false;

            if (comboBoxEntityTypeLookFor.Text.Length == 0)
            {
                this.buttonGoSearch.Enabled = false;
                return;
            }

            if (comboBoxEntityTypeLookFor.SelectedItems.Count > 10)
            {
                MessageBox.Show(ResFixer.Resources.LoadString("MaximumEntityExceedError") + comboBoxEntityTypeLookFor.SelectedItems.Count.ToString(), "Search Error", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                return;
            }

            for (int selIndex = 0; selIndex < comboBoxEntityTypeLookFor.SelectedItems.Count; selIndex++)
            {
                selectedEntities.Add((object)comboBoxEntityTypeLookFor.SelectedItems[selIndex].ToString());
            }
            _parentPane.changeScenario(3, selectedEntities, this.textBoxLookForText.Text.ToString(), ref thisRecord, RefreshOption.FromLink);
            
            /*BusinessEntityCollection becRetrievedEntities = null;
            string searchPattern = textBoxLookForText.Text;
            string searchIn = MainEntityName();
            int countOfEntities = -1;
            DisableControlsWhileLookUp();

            this.listViewOfRelatedRecordDetails.Enabled = false;
            this.listViewOfRelatedRecordDetails.Columns.Clear();
            DisablePaging();
            lblNoRelRecords.Visible = lblNoRelRecords.Enabled = false;
            if (CBoxSelectAllRelRec != null)
            {
                CBoxSelectAllRelRec.Visible = CBoxSelectAllRelRec.Enabled = false;
            }

            if ((searchPattern == null) || (searchPattern == string.Empty))
            {
                CreateAndShowANewLookUpDlg(searchIn, searchPattern);
                this.buttonGoSearch.Enabled = true;
                return;
            }

            MakeItLookBusy(global::CRMScenarios.Resources.PleaseWait);
            becRetrievedEntities = CrmConnector.DoRealSearchBringMinimal(searchIn, searchPattern, null);
            NotBusyAnyMore();

            if (becRetrievedEntities != null)
            {
                countOfEntities = becRetrievedEntities.BusinessEntities.Length;
            }

            switch (countOfEntities)
            {
                case -1:
                    this.FlagErrorOrWarning(global::CRMScenarios.Resources.ErrorInSearching, InfoOptions.Error);
                    break;

                case 0:
                    this.lblNoRecordFound.Visible = true;
                    this.lblNoRecordFound.BringToFront();
                    CreateAndShowANewLookUpDlg(searchIn, searchPattern);
                    break;

                case 1:
                    MakeItLookBusy(global::CRMScenarios.Resources.SingleRecordFound);
                    getDetailsOfTheEntityAndDisplay(becRetrievedEntities.BusinessEntities[0], searchIn);
                    NotBusyAnyMore();
                    break;

                default:
                    CreateAndShowANewLookUpDlg(searchIn, searchPattern);
                    break;
            } */
            this.buttonGoSearch.Enabled = true;
        }

        void RelatedGridDataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
        }
	}
}